﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Nortec.DBScriptsGenerator
{
    class Program
    {
        private static readonly string outputFileName = AppDomain.CurrentDomain.BaseDirectory + @"\DBScript.sql";
        private static string sourceDirectory;
        private const string searchPattern = "*.sql";
        
        static void Main(string[] args)
        {
            if (args.Length > 0)
                sourceDirectory = args[0];
            GenerateScripts();
        }

        private static void GenerateScripts()
        {
            string outPutDirectory = Path.GetDirectoryName(outputFileName);
            if (!Directory.Exists(outPutDirectory))
                Directory.CreateDirectory(outPutDirectory);

            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(outputFileName);
                var files = GetUniqueFileList(new DirectoryInfo(sourceDirectory));

                foreach (var fi in files)
                {   
                    var sr = new StreamReader(fi.Open(FileMode.Open, FileAccess.Read));
                    sw.WriteLine(sr.ReadToEnd());
                    sw.WriteLine();
                    sr.Close();
                }
            }
            finally
            {
                if (sw != null) sw.Close();
            }
        }
        
        private static List<FileInfo> GetUniqueFileList(DirectoryInfo directory)
        {
            var files = directory.GetFiles(searchPattern, SearchOption.AllDirectories);
            var uniqueList = new List<FileInfo>();
            var nameList = new List<string>();
            Array.Sort(files, new FileInfoComparer());
            
            foreach(var file in files)
            {
                if (!nameList.Contains(file.Name) && !file.Name.ToLower().StartsWith("setup"))
                {
                    nameList.Add(file.Name);
                    uniqueList.Add(file);
                }
            }
            return uniqueList;
        }
        
        // Ordena la lista descendentemente
        public class FileInfoComparer : IComparer<FileInfo>
        {
            public int Compare(FileInfo x, FileInfo y)
            {
                if (x == null && y == null)
                    return 0;
                
                if (x == null)
                    return 1;
                
                if (y == null)
                    return -1;
                
                return x.FullName.CompareTo(y.FullName)*-1;
            }
        }

    }
}
